package com.xyd.servlet;

import com.xyd.entity.News;
import com.xyd.service.NewsService;
import com.xyd.service.impl.NewsServiceImpl;
import com.xyd.util.TotalPageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 任梦强
 * @date 2021.1.11
 */
@WebServlet("/NewsServlet")
public class NewsServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String currPage=request.getParameter("pageIndex");

        if (currPage==null){
            currPage="1";
        }
        int pageIndex=Integer.parseInt(currPage);
        NewsService newsService=new NewsServiceImpl();

        int count=newsService.getNewsCount();
        TotalPageUtil totalPageUtil=new TotalPageUtil();

        int totalPages= TotalPageUtil.getTotalPage(count,8);

        if (pageIndex<1){
            pageIndex=1;
        }
        if (pageIndex>totalPages){
            pageIndex=totalPages;
        }

        List<News>news=newsService.getNewsByPage((pageIndex-1)*8,8);

        request.setAttribute("news",news);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("totalPages",totalPages);
        request.getRequestDispatcher("manage/news.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
